package com.alan.swagger2.utils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/*
 * 利用HttpClient进行post请求的工具类
 */
public class HttpClientUtil {
	/**
	 * 日志对象
	 */
	protected static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
	/**
	 * 
	 * @param url
	 * @param map
	 * @param charset
	 * @return
	 */
	public static String doPost(String url,Map<String,String> map,String charset){
		HttpClient httpClient = null;
		HttpPost httpPost = null;
		String result = null;
		/*System.out.println("POST url : " + url);
		System.out.println("POST parameter : " + map.toString());*/
		logger.info("POST url : " + url);
		logger.info("POST parameter : " + map.toString());
		try{
			httpClient = new SSLClient();
			httpPost = new HttpPost(url);
			//设置参数
			List<NameValuePair> list = new ArrayList<NameValuePair>();
			Iterator iterator = map.entrySet().iterator();
			while(iterator.hasNext()){
				Entry<String,String> elem = (Entry<String, String>) iterator.next();
				list.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));
			}
			if(list.size() > 0){
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,charset);
				httpPost.setEntity(entity);
			}
			HttpResponse response = httpClient.execute(httpPost);
			if(response != null){
				HttpEntity resEntity = response.getEntity();
				if(resEntity != null){
					result = EntityUtils.toString(resEntity,charset);
				}
			}
		}catch(Exception ex){
			ex.printStackTrace();
			return null;
		}
		return result;
	}
	
	
	/**
	 * post 请求数据是xml的
	 * @param url
	 * @param xml
	 * @param charset
	 * @return
	 */
	public static String doPostXml(String url,String xml,String charset){
		HttpClient httpClient = null;
		HttpPost httpPost = null;
		String result = null;
		System.out.println("POST parameter : " + xml);
		try{
			httpClient = new SSLClient();
			httpPost = new HttpPost(url);
			//设置参数
			if(null != xml && !xml.equals("")){
				StringEntity entityParams = new StringEntity(xml, charset);
	            httpPost.setEntity(entityParams);
	            httpPost.setHeader("Content-Type", "text/xml;charset=ISO-8859-1");
			}
			/*HttpResponse response = null;
			for (int i = 0; i < 3; i++) {
				response = httpClient.execute(httpPost);
				if(null != response && null != response.getEntity()){
					//result = EntityUtils.toString(response.getEntity(),charset);
					break;
				}
			}
			if(response != null){
				HttpEntity resEntity = response.getEntity();
				if(resEntity != null){
					result = EntityUtils.toString(resEntity,charset);
				}
			}*/
			HttpResponse response = httpClient.execute(httpPost);
			if(response != null){
				HttpEntity resEntity = response.getEntity();
				if(resEntity != null){
					result = EntityUtils.toString(resEntity,charset);
				}
			}
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return result;
	}
	
	
	/**
	 * http 不加密 上传文件
	 * 上传文件(用的是httpclient,httpcore,commons-httpclient 包)
	 * @author alan
	 * @param urlStr 请求地址
	 * @param node【】 键
	 * @param values【】 值
	 * @param files【】 文件
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 * @throws IllegalStateException
	 * @throws HttpHostConnectException
	 * @throws Exception
	 */
	public static String executeHttpPostUpLoadFile(String urlStr,
			String[] node, String[] values, File[] files)
			throws ClientProtocolException, IOException, IllegalStateException,
			HttpHostConnectException, Exception {

		for (int i = 1; i < node.length; i++) {
			if (i == 1) {
				urlStr = urlStr + "?" + node[i] + "=" + values[i];
			} else {
				urlStr = urlStr + "&" + node[i] + "=" + values[i];
			}
		}

		PostMethod p = new PostMethod();
		URI uri = new URI(urlStr);
		p.setURI(uri);
		// 设置param
		Part[] params = new Part[node.length + files.length];
		// 传节点
		logger.info("传节点");
		for (int i = 0; i < node.length; i++) {
			System.out.println(node[i]);
			System.out.println(values[i]);
			StringPart stringPart = new StringPart(node[i], values[i]);
			// 中文要用这个
			stringPart.setCharSet("UTF-8");
			params[i] = stringPart;
		}
		// 传文件
		logger.info("传文件");
		for (int i = 0; i < files.length; i++) {
			//对应MultipartFile的key
			String name = files[i].getName();
			FilePart filePart = new FilePart(name, files[i]);
			filePart.setCharSet("UTF-8");
			params[node.length + i] = filePart;
		}
		try {
			MultipartRequestEntity post = new MultipartRequestEntity(params,
					p.getParams());
			p.setRequestEntity(post);
			org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
			client.getHttpConnectionManager().getParams()
					.setConnectionTimeout(10000);
			client.getHttpConnectionManager().getParams().setSoTimeout(35000);
			int result = client.executeMethod(p);
			if (result == 200) {
				return p.getResponseBodyAsString();
			} else {
				String error = "File Upload Error HttpCode=" + result;
				System.out.println(error);
				//logger.info("********************");
				return null;
			}
		} catch (Exception e) {
			return null;
		} finally {
			//logger.info("--------------");
			p.releaseConnection();
		}
	}

	/**
	 * 上传文件(用的是httpclient,httpcore,httpmime 包)
	 * @param url
	 * @param f
	 * @param fileName
	 * @param contentType
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public String upload(String url, File f, String fileName,
								String contentType) throws ClientProtocolException, IOException {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		String result = null;
		try {
			if (contentType == null) {
				contentType = "image/pjpeg";
			}
			HttpPost httppost = new HttpPost(url);
			FileBody file = new FileBody(f, ContentType.create(contentType),
					fileName);

			HttpEntity reqEntity = MultipartEntityBuilder.create()
					.addPart(fileName, file)
					.build();

			httppost.setEntity(reqEntity);
			logger.info(httppost.getRequestLine().toString());
			CloseableHttpResponse response = httpclient.execute(httppost);
			try {
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					logger.info("Responseh: " + resEntity.getContentLength());
					result = EntityUtils.toString(resEntity);
					logger.info("Response: " + result);
				}
			} finally {
				response.close();
			}
		} finally {
			httpclient.close();
		}
		return result;
	}
	
}